package leetcode;

import javax.swing.tree.TreeNode;

/**
 * 有序数组转换为二叉树
 */
public class Solution24 {
    public TreeNode sortedArrayToBST(int[] nums) {
        return sortedArrayToBST(nums, 0 ,nums.length);
    }

    public TreeNode sortedArrayToBST(int[] nums , int left , int right){
        if(left >= right){
            return null;
        }
        if(right - left == 1){
            return new TreeNode(nums[left]);
        }
        int mid  = left + (right - left) / 2;
        //将中间节点设置为二叉树的根节点
        TreeNode root = new TreeNode(nums[mid]);
        root.left = sortedArrayToBST(nums, left , mid);
        root.right = sortedArrayToBST(nums , mid + 1 ,right);

        return root;
    }
}
